<template>
  <div class="product-list">
    <h2>产品列表</h2>
    <ul>
      <li v-for="product in products" :key="product.id">
        <img :src="product.image" :alt="product.name">
        <h3>{{ product.name }}</h3>
        <p>价格: {{ product.price }}</p>
        <button @click="addToCart(product)">添加到购物车</button>
      </li>
    </ul>
  </div>
</template>

<script>
import { mapActions } from 'vuex';

export default {
  name: 'ProductList',
  data() {
    return {
      products: [
        {
          id: 1,
          name: '有线耳机',
          price: 99,
          image: 'src/assets/img_5.png'
        },
        {
          id: 2,
          name: '智能手机',
          price: 19999,
          image: 'src/assets/img_7.png'
        },
        {
          id: 3,
          name: '头戴式耳机',
          price: 199,
          image: 'src/assets/img_6.png'
        },
        {
          id: 4,
          name: 'U盘',
          price: 199,
          image: 'src/assets/img_8.png'
        },
        {
          id: 5,
          name: '游戏手柄',
          price: 199,
          image: 'src/assets/img_9.png'
        },
        {
          id: 6,
          name: '蓝牙耳机',
          price: 55,
          image: 'src/assets/img_10.png'
        },
        {
          id: 7,
          name: '相机',
          price: 1999,
          image: 'src/assets/img_11.png'
        }


      ]
    };
  },
  methods: {
    ...mapActions(['addToCart']),
    addToCart(product) {
      // 调用映射后的addToCart方法，注意这里要使用this.$store.dispatch或者this[actionName]的形式
      this.$store.dispatch('addToCart', product);
      // 或者使用 this.addToCart(product)，但要确保在组件的上下文中this.addToCart指向映射后的方法，而不是自身的方法定义
    }
  }
};
</script>

<style scoped>
.product-list ul {
  list-style: none;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.product-list li {
  border: 1px solid #ccc;
  padding: 10px;
  text-align: center;
}

.product-list img {
  max-width: 50%;
  height: auto;
}
</style>